<template>
  <div class="flex flex-col gap-4 h-full">
    <!-- 多条折线图示例 -->
    <div class="bg-white/96 rounded-xl shadow-lg flex-1 overflow-hidden">
      <div class="w-full bg-[#2B6E50] py-2 flex justify-between items-center px-5">
        <span class="text-white text-[18px] font-bold">森林生长监测</span>
        <el-select v-model="activeDevice" placeholder="请选择" placement="bottom-end" size="small"
          popper-class="device-select" class="select-wrap" @change="changeDevice">
          <template #label="{ label, value }">
            <div class="flex items-center justify-between text-white">
              <span>{{ value }}</span>
              <span class="text-white/70">{{ getStatus }}</span>
            </div>
          </template>
          <el-option v-for="item in devicesInfo" :key="item.deviceId" :value="item.deviceId">
            <div class="flex items-center justify-between">
              <div>{{ item.deviceId }}</div>
              <div class="flex items-center gap-1"><span class="block" :class="{ 'on-line': item.status === 0 }" />{{ item.status === 0 ? '在线' : '离线' }}</div>
            </div>
          </el-option>
        </el-select>
      </div>
      <LineChart :x-axis-data="multiLineData.xAxis" :y-axis-name="yAxisName" :data="multiLineData.series"
        height="calc(90%)" />
    </div>
    <!-- 生境监测 -->
    <div class="flex-1">
      <HabitatMonitor title="湿度监测" />
    </div>
    <!-- 视频流 -->
    <div class="bg-white/96 rounded-xl shadow-lg overflow-hidden flex-1">
      <div class="w-full bg-[#2B6E50] py-2">
        <span class="text-white text-[18px] font-bold ml-5">物候监测</span>
      </div>
      <div style="height:calc(100% - 2.6rem)">
        <el-image :src="picUrl" fit="contain" class="h-full" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import LineChart from '../LineChart.vue'
import HabitatMonitor from './HabitatMonitor.vue'
import { getDevicesInfo, getDeviceLineData, getPicUrl } from '@/api/forest-management'

// 定义设备信息类型
interface DeviceInfo {
  deviceId: string
  status: number
}

// 定义折线图数据项类型
interface LineDataItem {
  time: string
  value: string
}

// 定义API返回的折线图数据类型
interface LineDataResponse {
  type: string
  unit: string
  data: LineDataItem[]
}

// 定义图表系列数据类型
interface ChartSeries {
  name: string
  data: number[]
  color: string
}

// 定义多线图数据类型
interface MultiLineData {
  xAxis: string[]
  series: ChartSeries[]
}

// 获取设备信息
const devicesInfo = ref<DeviceInfo[]>([])
const activeDevice = ref<string>('')
const getDevices = async () => {
  try {
    const res = await getDevicesInfo()
    console.log(res);
    devicesInfo.value = res
    activeDevice.value = res[0].deviceId
    getLineData()
  } catch (error) {

  }
}

// Y轴名称（包含单位）
const yAxisName = ref('')

// 折线图数据
const multiLineData = ref<MultiLineData>({
  xAxis: [],
  series: [
    {
      name: '',
      data: [],
      color: '#60AE8E'
    },
  ]
})

// 获取折线图数据
const getLineData = async () => {
  try {
    const res: LineDataResponse = await getDeviceLineData(activeDevice.value)
    // 处理时间轴数据，格式化为 月-日 时:分
    const xAxis = res.data.map(item => {
      const date = new Date(item.time)
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${month}-${day} ${hours}:${minutes}`
    })

    // 处理数据值
    const data = res.data.map(item => parseFloat(item.value))

    // 设置Y轴名称（包含单位）
    yAxisName.value = `${res.type}(${res.unit})`

    // 更新图表数据
    multiLineData.value = {
      xAxis,
      series: [
        {
          name: `${res.type}(${res.unit})`, // 使用返回的类型和单位作为系列名称
          data,
          color: '#60AE8E'
        }
      ]
    }
  } catch (error) {
    console.error('获取折线图数据失败:', error)
  }
}

const getStatus = computed(() => {
  return devicesInfo.value.find(item => item.deviceId === activeDevice.value)?.status === 0 ? '在线' : '离线'
})

const changeDevice = () => {
  getLineData()
}

// 获取物候图片地址
const picUrl = ref('')
const getPic = async () => {
  try {
    const res = await getPicUrl()
    console.log(res);
    
    picUrl.value = res
  } catch (error) {
    console.error('获取物候图片失败:', error)
  }
}

onMounted(() => {
  getPic()
  getDevices()
})
</script>

<style scoped lang="scss">
.select-wrap {
  width: 140px !important;

  :deep(.el-select__wrapper) {
    background-color: transparent;
    border-radius: 30px;
  }
}
</style>
<style>
.device-select {
  min-width: 200px;
  border-radius: 10px;

  .el-select-dropdown__item {
    border-bottom: 1px solid #C4C4CC;

    &:last-child {
      border-bottom: none;
    }

    .block{
      width: 8px;
      height: 8px;
      border-radius: 2px;
      background-color: #C4C4CC;

      &.on-line{
        background-color: #54A539;
      }
    }
  }
}
</style>
